<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="关联平台分类"
    width="1200"
    show-footer
    show-zoom
    resize
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <template #default>
      <div>说明：根据最小分类进行映射</div>
      <div class="py-2">
        <el-radio-group v-model="form.platform_code">
          <el-radio-button
            v-for="(item, index) in platformOptions"
            :label="item.platform_code"
            :value="item.platform_code"
            :key="index"
            :disabled="item.platform_code != 'ebay'"
            >{{ item.platform_name }}</el-radio-button
          >
        </el-radio-group>
      </div>
      <div class="py-2">
        <el-tabs v-model="form.site_id" @tab-click="handleTabClick">
          <el-tab-pane
            v-for="(item, index) in siteOptions"
            :name="item.marketplace_id"
            :label="item.site_code"
            :value="item.site_code"
            :key="index"
            :props="item"
          >
            <template #label>{{ item.site_code }}({{ item.site_name }})</template>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="flex justify-between mb-2">
        <div class="w-[900px] h-[500px] overflow-y-auto">
          <el-tree
            v-if="is_update"
            ref="treeRef"
            style="max-width: 600px"
            :props="treeProps"
            :load="loadNode"
            lazy
            :default-expanded-keys="defaultExpandedKeys"
            node-key="categoryId"
          >
            <template #default="{ node, data }">
              <div class="flex items-center justify-between w-[1000px]">
                <span
                  class="tree-label flex justify-start items-center text-sm text-[#333333]"
                >
                  <el-checkbox v-if="data.leaf" v-model="data.checked" />

                  <span class="ml-2 text-center"> {{ node.label }}</span>
                </span>
                <div class="w-[200px]" v-if="data.leaf">
                  <el-input
                    v-model="data.keyword"
                    size="small"
                    placeholder="请输入备注"
                  ></el-input>
                </div>
              </div>
            </template>
          </el-tree>
        </div>
        <el-button type="primary" @click="handleSave()">站点分类保存</el-button>
      </div>
    </template>
    <template #footer>
      <el-button @click="close">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup name="AssociatedPlatform">
import { reactive, ref, toRefs, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import useCommonStore from "@/store/modules/common";
import {
  queryEbayBaseCategory,
  getBaseBackColumnsdetails,
  batchSearchCategoryRoad,
  relationPlatform,
} from "../api.js";

const platforms = ["ebay"];

const commonStore = useCommonStore();
const platformOptions = computed(() => {
  if (!commonStore.platformOptions) {
    commonStore.getPlatformList();
  }
  let options = commonStore.platformOptions.filter((i) => {
    if (platforms.includes(i.platform_code)) {
      return i;
    }
  });

  return options;
});

const siteOptions = computed(() => {
  if (platformOptions.value.length) {
    const findOPions = platformOptions.value.find(
      (i) => form.value.platform_code == i.platform_code
    );
    // form.value.site_id = findOPions?.sites[0].site_id;
    // form.value.site_code = findOPions?.sites[0].site_code;
    return findOPions?.sites;
  } else {
    return [];
  }
});

const emits = defineEmits(["query"]);
const props = defineProps({
  treeData: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

const data = reactive({
  form: {
    platform_code: "",
    site_id: "",
  },
  visible: false,
  defaultExpandedKeys: [],
  is_update: false,
  load: false,
});
const { form, visible, defaultExpandedKeys, is_update, load } = toRefs(data);

const open = async (data) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  // if (type == "add") {
  form.value.platform_code = "ebay";
  form.value.site_id = siteOptions.value[0].marketplace_id;
  form.value.site_code = siteOptions.value[0].site_code;
  form.value.id = data.id;
  getDetail();
  // } else {
  //   form.value = data;
  //   form.value.id = data.category_id;
  //   form.value.base_category_platform = [data];

  //   console.log(form.value);
  //   getDefaultKeys();
  //   is_update.value = true;
  // }

  visible.value = true;
};

onMounted(() => {});

const close = () => {
  is_update.value = false;
  visible.value = false;
};

defineExpose({ open });

const treeProps = {
  label: "categoryName",
  children: "zones",
  isLeaf: "leaf",
};

const treeRef = ref();
const handleTabClick = (tab) => {
  form.value.site_code = tab.props.label;
  form.value.site_id = tab.props.name;
  is_update.value = false;
  getDefaultKeys();
  nextTick(() => {
    is_update.value = true;
  });
};

const loadNode = (node, resolve, reject) => {
  defaultExpandedKeys.value.forEach((key) => {
    if (treeRef.value) {
      const defaultNode = treeRef.value.getNode(key);
      if (defaultNode) {
        defaultNode.loaded = true;
      }
    }
  });

  return queryBaseCategory(node).then(resolve).catch(reject);
};

const queryBaseCategory = async (node) => {
  try {
    const res = await queryEbayBaseCategory({
      categoryId: node?.data?.categoryId,
      siteId: form.value.site_id,
      queryType: node?.level == 0 ? "F" : "C",
    });
    const data = res.data.map((i) => {
      const find = form.value.base_category_platform.find(
        (j) => j.site_id == form.value.site_id
      );
      if (find) {
        const findDetail = find.base_category_platform_detail.find(
          (j) => j.platform_category_id == i.categoryId
        );
        if (findDetail) {
          i.id = findDetail.id;
          i.checked = true;
          i.keyword = findDetail.keyword;
        }
      }
      return {
        ...i,
      };
    });

    return data;
  } catch (e) {
    throw Error(e);
  }
};

const getDetail = async (data) => {
  try {
    const res = await getBaseBackColumnsdetails({
      id: form.value.id,
    });
    form.value = {
      ...form.value,
      ...res.data,
    };
    getDefaultKeys();
    is_update.value = true;
  } catch (e) {
    throw Error(e);
  }
};

const getDefaultKeys = () => {
  const defaultKeys = form.value.base_category_platform
    .filter((i) => i.site_id == form.value.site_id)
    .flatMap((i) => i.base_category_platform_detail || [])
    .flatMap((j) => j.all_platform_category_id || [])
    .reduce((acc, id) => acc.add(id), new Set());

  defaultExpandedKeys.value = Array.from(defaultKeys);
};

const getCheckNode = (root, checkNode) => {
  const stack = [root];
  while (stack.length > 0) {
    const node = stack.pop();
    if (node.data.checked) {
      checkNode.push(node.data);
    }
    if (node.childNodes && node.childNodes.length) {
      for (const child of node.childNodes) {
        stack.push(child);
      }
    }
  }
};

const getCategoryRoad = async (keywordList) => {
  try {
    const res = await batchSearchCategoryRoad({
      keywordList,
      siteId: form.value.site_id,
      type: 1,
    });
    return res.data;
  } catch (e) {
    throw Error(e);
  }
};

const handleSave = async () => {
  const root = treeRef.value.root;
  if (root.childNodes.length == 0) {
    ElMessage.error("当前站点暂无可操作分类");
    return;
  }
  const checkNode = [];
  getCheckNode(root, checkNode);
  const categoryIds = checkNode.map((i) => i.categoryId);
  const categoryRoad = await getCategoryRoad(categoryIds);
  const base_category_platform_detail = checkNode.map((i) => {
    i.all_platform_category_id = categoryRoad[i.categoryId][0]
      .filter((j) => j.id)
      .map((j) => j.id);
    i.platform_category_id = i.categoryId;
    return i;
  });

  try {
    let base_category_platform = null;

    if (form.value.base_category_platform.length == 0) {
      base_category_platform = [
        {
          platform_code: "ebay",
          platform_id: 1,
          site_code: form.value.site_code,
          site_id: form.value.site_id,
          base_category_platform_detail,
        },
      ];
    } else {
      const findIndex = form.value.base_category_platform.findIndex(
        (i) => i.site_id == form.value.site_id
      );
      if (findIndex == -1) {
        form.value.base_category_platform.push({
          platform_code: "ebay",
          platform_id: 1,
          site_code: form.value.site_code,
          site_id: form.value.site_id,
          base_category_platform_detail,
        });

        base_category_platform = form.value.base_category_platform;
      } else {
        form.value.base_category_platform[
          findIndex
        ].base_category_platform_detail = base_category_platform_detail;

        base_category_platform = form.value.base_category_platform;
      }
    }

    const res = await relationPlatform({
      id: form.value.id,
      base_category_platform,
    });
    ElMessage.success("保存成功");
    is_update.value = false;
    getDetail();
  } catch (e) {
    throw Error(e);
  }
};
</script>
<style lang="scss"></style>
